#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- 
# --
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2021/7/7 11:57
# Email lmay@lmaye.com
# ----------------------------------------------------------
from datetime import datetime

from PyQt5.QtCore import pyqtSignal, QThread

from core.handler import thread_handler


class SyncThread(QThread):
    """
            SyncExecuteThread

            -- 同步执行线程
        """
    signal_out = pyqtSignal(str)

    def __init__(self, parent=None):
        super(SyncThread, self).__init__(parent)
        # 读取数据路径
        self.int_path = None
        # 文件输出路径
        self.out_path = None
        # 取数文件
        self.take_file = None
        # 生成类型
        self.cr_type = None
        # 取数条件
        self.where_columns = None
        # 生成列名
        self.source_columns = None
        # 插入列名
        self.add_columns = None

    def set_param(self, int_path, out_path, take_file, cr_type, where_columns, source_columns, add_columns):
        self.int_path = int_path
        self.out_path = out_path
        self.take_file = take_file
        self.cr_type = cr_type
        self.where_columns = where_columns
        self.source_columns = source_columns
        self.add_columns = add_columns

    def run(self):
        """
            执行
        """
        self.signal_out.emit("{} -->>> 开始执行 ...".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
        try:
            threads = thread_handler.thread_list(self.int_path, self.out_path, self.take_file,
                                                 str(self.source_columns).split(","), self.where_columns,
                                                 str(self.add_columns).split(","), self.signal_out)
            for t in threads:
                t.start()
            for t in threads:
                t.join()
            thread_handler.merge_files(self.out_path, self.cr_type, self.signal_out)
        except Exception as e:
            self.signal_out.emit("{} 执行异常: {}".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), e))
            return None
        self.signal_out.emit("======================= 执行完成 =======================")
